from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
import time


# 定义一个黑名单
ban = {}

BAN_SECOND = 2  # 请求时间段
BAN_LIMIT = 10  # 请求频率
BAN_TIME = 120  # BAN时长


class AuthorityVerification(MiddlewareMixin):

    def process_request(self, request):
        # 获取远程主机IP
        ip = str(request.META.get("REMOTE_ADDR"))
        # 如果是第一次请求则直接放行
        if ban.get(ip) is None:
            ban[ip] = {"total": 1, "time": int(time.time())}
        # 如果不是第一次请求 则判断是一次请求时间与这次的间隔是否小于2s
        elif ban[ip]['time'] > int(time.time()) - BAN_SECOND:
            # 2s内的同IP 再判断次数是否大于BAN_LIMIT
            if ban[ip]['total'] > BAN_LIMIT:
                # 如果是超过10次请求则 ip的time移至BAN的解封时间
                ban[ip]['ban'] = int(time.time()) + BAN_TIME
                return JsonResponse({"state": 100, "message": "请求拒绝", "data": {}}, safe=False)
            # 不大于10次就再加一次
            ban[ip]["total"] += 1
        else:
            # 获取dict里面的ban属性
            tm = ban[ip].get('ban')
            # 如果已经ban了 则直接返回
            if tm is not None and tm > int(time.time()):
                return JsonResponse({"state": 100, "message": "请求拒绝", "data": {}}, safe=False)
            # 如果已经过了ban时间则移除黑名单
            del ban[ip]

    def process_exception(self, request, exception):
        print('AuthorityVerification error')
        return JsonResponse({"state": 500, "message": "服务器错误", "data": str(exception)}, safe=False)

    def process_response(self, request, response):
        return response
